import backtrader as bt
import akshare as ak
import pandas as pd

# 获取股票数据
stock_df = ak.stock_zh_a_daily(symbol="sh600000", start_date="20200101", end_date="20211231")
stock_df.index = pd.to_datetime(stock_df.index)

class SmaCross(bt.Strategy):
    params = (('pfast', 10), ('pslow', 30),)

    def __init__(self):
        sma_fast = bt.indicators.SMA(period=self.params.pfast)
        sma_slow = bt.indicators.SMA(period=self.params.pslow)
        self.crossover = bt.indicators.CrossOver(sma_fast, sma_slow)

    def next(self):
        if not self.position:
            if self.crossover > 0:
                self.buy()
        elif self.crossover < 0:
            self.sell()

cerebro = bt.Cerebro()
data = bt.feeds.PandasData(dataname=stock_df)
cerebro.adddata(data)
cerebro.addstrategy(SmaCross)
cerebro.run()
cerebro.plot()
